package com.micro.turtle.runner;

import cn.hutool.core.collection.CollectionUtil;
import com.micro.turtle.anon.CmdRunner;
import com.micro.turtle.constant.Cmd;
import com.micro.turtle.constant.Url;
import com.micro.turtle.constant.Url.PipelineUri;
import com.micro.turtle.model.Pipeline;
import com.micro.turtle.model.resp.PipelineResp;
import com.micro.turtle.util.Api;
import com.micro.turtle.util.Log;
import java.util.List;

/**
 * PipelineRunner
 *
 * @author jason.lv
 * @since 2022/1/20 16:23
 */
public class PipelineRunner {

    @CmdRunner
    public static class ListRunner extends Runner {

        public ListRunner() {
            super(Cmd.PIPES);
        }

        @Override
        void exec() {
            String next = scannerNext("输入项目ID:");
            print(list(Integer.valueOf(next)));
        }
    }

    @CmdRunner
    public static class CreateRunner extends Runner {

        public CreateRunner() {
            super(Cmd.PIPE_CREATE);
        }

        @Override
        void exec() {
            String next = scannerNext("输入项目ID:");
            PipelineResp pipeline = create(Integer.valueOf(next));
            Log.info("Pipeline >>>>> Id:%s ||| %s ||| %s ||| %s", pipeline.getId(), pipeline.getProjectId(), pipeline.getStatus(), pipeline.getRef());
        }
    }

    public static void print(List<Pipeline> pipelines) {
        if (CollectionUtil.isEmpty(pipelines)) {
            Log.info("Pipelines >>>>> has nothing");
            return;
        }
        for (Pipeline pipeline : pipelines) {
            Log.info("Pipeline >>>>> Id:%s ||| %s ||| %s ||| %s", pipeline.getId(), pipeline.getProjectId(), pipeline.getStatus(), pipeline.getRef());
        }
    }

    public static List<Pipeline> list(Integer projectId) {
        Url url = Url.create(PipelineUri.LIST).project(projectId);
        return Api.getList(url, Pipeline.class);
    }

    public static PipelineResp create(Integer projectId) {
        Url url = Url.create(PipelineUri.CREATE).project(projectId);
        return Api.post(url, PipelineResp.class);
    }

    public static PipelineResp retry(Integer projectId, Integer pipelineId) {
        Url url = Url.create(PipelineUri.RETRY).project(projectId).pipeline(pipelineId);
        return Api.post(url, PipelineResp.class);
    }

    public static PipelineResp cancel(Integer projectId, Integer pipelineId) {
        Url url = Url.create(PipelineUri.CANCEL).project(projectId).pipeline(pipelineId);
        return Api.post(url, PipelineResp.class);
    }

    public static PipelineResp delete(Integer projectId, Integer pipelineId) {
        Url url = Url.create(PipelineUri.DELETE).project(projectId).pipeline(pipelineId);
        return Api.post(url, PipelineResp.class);
    }
}
